from flask import request,g,session,redirect,url_for,Response
from application import db
from apps.front.urls import BP
from apps.crm.urls import BP as CMS
from apps.front.models import FrontUser
from apps.crm.models import User
import jwt
import config

@BP.before_request
def login_require():
    endpoint = request.endpoint
    if request.method != 'OPTIONS':
        for i in config.PUBLIC_URL:
            res = i.match(endpoint)
            if res:
                jwt_str = request.headers.get('AUTH')
                if not jwt:
                    return Response("未登录",status=403)
                try:
                    payload = jwt.decode(jwt_str,key=config.SECRET_KEY)
                    assert payload.get('user_id') and payload.get('user_type') == 'admin', Exception('未登录')
                except Exception as e:
                    print(e)
                    return Response("未登录",status=403)
                user_id = payload['user_id']
                user = db.session.query(FrontUser).filter(FrontUser.id == user_id).first()
                if not user:
                    return Response("未登录",status=403)

                g.user = user
                

        



@CMS.before_request
def login_require():
    endpoint = request.endpoint
    if request.method != 'OPTIONS':
        for i in config.PUBLIC_URL:
            res = i.match(endpoint)
            if res:
                jwt_str = request.headers.get('AUTH')
                if not jwt:
                    return Response("未登录",status=403)
                try:
                    payload = jwt.decode(jwt_str,key=config.SECRET_KEY)
                    assert payload.get('user_id') and payload.get('user_type') == 'admin', Exception('未登录')
                except Exception as e:
                    return Response("未登录",status=403)
                user_id = payload['user_id']
                user = db.session.query(User).filter(User.id == user_id).first()
                if not user:
                    return Response("未登录",status=403)

                g.user = user
